import { Component, Show, createEffect, createSignal } from 'solid-js'
import { Transition } from 'solid-transition-group'
import S from './Info.module.styl'
import { useGame } from './game'
import { uniqTimer } from './utils'
import Versus from './Versus'
import { Skill } from './skill'

// 对象类型，每次都变，刚好keyed
type Content = {
  type: 'str'
  str: string
} | {
  type: 'vs'
  left: Skill
  right: Skill
}

const mkStr = (str: string): Content => ({ type: 'str', str })

const Info: Component = () => {
  const { store } = useGame()
  const [content, setContent] = createSignal<Content>()

  const getInfo = (): Content[] => {
    const { record, result } = store
    if (record.length == 0) return [mkStr('开始游戏')]
    const [left, right] = record[record.length - 1]
    const versus: Content = { type: 'vs', left, right }
    switch (result) {
      case 0: return [versus]
      case 1: return [versus, mkStr('我方胜利')]
      case -1: return [versus, mkStr('对方胜利')]
    }
  }

  const [setIvInfo, clearIvInfo] = uniqTimer(setInterval, clearInterval)
  createEffect(() => {
    const info = getInfo()
    setContent(info[0])
    if (info.length > 1) {
      let i = 1
      setIvInfo(() => {
        setContent(info[i])
        i++
        if (i >= info.length) clearIvInfo()
      }, 1000)
    } else {
      clearIvInfo()
    }
  })

  return <Transition appear={true} enterClass={S.enter} exitToClass={S.exit_to}>
    <Show when={content()} keyed>{ct =>
      ct.type == 'str' ? <div class={S.current}>{ct.str}</div> :
        <Versus left={ct.left} right={ct.right} classList={{ [S.current]: true }}></Versus>
    }</Show>
  </Transition>
}

export default Info